package com.ywb.prototype;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.awt.*;
import java.io.*;

/**
 * @Author ywb
 * 浅拷贝
 */
@Data
@AllArgsConstructor
public class Sheep implements Cloneable, Serializable{
    private String name;
    private int age;
    private Color color;
    public Sheep friend;

    @Override
    protected Object clone() {
        Sheep sheep = null;
        try{
//
            sheep = (Sheep) super.clone();
//            1.深拷贝,对每个引用类型单独进行clone
            sheep.friend = (Sheep) sheep.friend.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return sheep;
    }

    public Object deepClone(){
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        try{
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);

            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            return ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }finally {
            try{
                bos.close();
                oos.close();
                bis.close();
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
